package com.feishi.project.opencv.camera;

import com.feishi.core.media.opencv.util.OpenCvUtil;
import com.feishi.core.util.common.EncryptUtil;
import com.feishi.project.opencv.websocket.WebSocketServer;
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-5-2 16:22
 **/
@Component
public class Camara {
    static {
        OpenCvUtil.loadLibrary();
    }
    @Autowired
    private WebSocketServer webSocketServer;


    @PostConstruct
    public void init(){
        VideoCapture camera = new VideoCapture();
        camera.open(0);

        Map map =new HashMap();
        if (!camera.isOpened()) {
            System.out.println("Camera Error");
        } else {
            Mat frame = new Mat();

            while (true){
                camera.read(frame);
                byte[] bytes = OpenCvUtil.MatToBytes(frame);

                EncryptUtil.encodeBase64(bytes);
                String head="data:image/png;base64,";
                map.put("img",EncryptUtil.encodeBase64(bytes));
                WebSocketServer.broadcast(map);

                try {
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
